<template>
  <div class="selector-wrap">
    <div>
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="keywords" label="关键字">
          <el-input
            v-model="queryParams.keywords"
            placeholder="用户名/姓名"
            clearable
            @keyup.enter="handleQuery"
            style="width: 140px"
          />
        </el-form-item>
        <el-form-item label="部门" prop="deptId">
          <el-tree-select
            v-model="queryParams.deptId"
            placeholder="请选择所属分类"
            :data="depOptions"
            filterable
            check-strictly
            :render-after-expand="false"
            style="width: 160px"
            clearable
          />
        </el-form-item>
        <el-form-item label="岗位" prop="jobId">
          <el-select
            v-model="queryParams.jobId"
            placeholder="请选择"
            style="width: 160px"
            clearable
          >
            <el-option
              v-for="item in jobOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item class="search-buttons">
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table
      ref="tableRef"
      :data="tableDatas"
      highlight-current-row
      :row-class-name="tableRowClassName"
      @current-change="handleCurrentChange"
      @selection-change="handleSelectionChange"
    >
      <el-table-column v-if="!props.isSingle" type="selection" width="50" align="center" />
      <el-table-column v-if="props.isSingle" width="55" align="center" />
      <el-table-column label="用户名" prop="username" />
      <el-table-column label="姓名" align="center" prop="realName" />
      <el-table-column label="部门" align="center" prop="departmentName" />
      <el-table-column label="手机" align="center" prop="phone" />
      <el-table-column label="邮箱" align="center" prop="email" />
    </el-table>

    <pagination
      v-if="total > 0"
      v-model:total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="handleQuery"
    />
  </div>
</template>

<script setup lang="ts">
import { defineProps, defineEmits } from "vue";
import UserAPI, { UserPageQuery, UserPageVO } from "@/api/system/user.api";
import DeptAPI, { DeptVO } from "@/api/system/dept.api";
import JobAPI, { JobPageVO } from "@/api/system/job.api";

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => [],
  },
  /** 是否单选 */
  isSingle: {
    type: Boolean,
    required: false,
    default: false,
  },
});

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
}) as UserPageQuery;

const depOptions = ref<DeptVO[]>();
const jobOptions = ref<JobPageVO[]>();
const tableRef = ref();
const emit = defineEmits(["update:modelValue", "selection-change"]);

const checked = ref<UserPageVO>(); //单选时的已选
const checkedList = ref<UserPageVO[]>([]); //多选时的已选列表

// 当前行选中（单选）
const handleCurrentChange = (selection: UserPageVO) => {
  if (!props.isSingle) return;
  checked.value = selection;
};

// 已选列表发生变化（多选）
const handleSelectionChange = (selection: UserPageVO[]) => {
  checkedList.value = selection;
  emit("update:modelValue", selection);
  emit("selection-change", selection);
};

// 获取已选数据（单选）
function getChecked(): UserPageVO | undefined {
  return checked.value;
}

// 获取已选数据（多选）
function getCheckedList(): UserPageVO[] {
  return checkedList.value || [];
}

const total = ref(0);
const tableDatas = ref<UserPageVO[]>();

const handleQuery = () => {
  queryParams.departmentIds = queryParams.deptId ? [queryParams.deptId] : undefined;
  queryParams.deptDeepSearch = !!queryParams.deptId;
  UserAPI.getPage(queryParams).then((data) => {
    tableDatas.value = data.list;
    total.value = data.total;
  });
};

const handleResetQuery = () => {
  queryParams.keywords = "";
  queryParams.pageNum = 1;
  queryParams.jobId = undefined;
  queryParams.deptId = undefined;
  queryParams.departmentIds = [];
  handleQuery();
};

onMounted(async () => {
  depOptions.value = await DeptAPI.getOptions();
  jobOptions.value = await JobAPI.getOptions();
  handleResetQuery();
});

// 行样式
const tableRowClassName = ({ row }: { row: UserPageVO }) => {
  if (!props.isSingle) return "";
  if (row.id === checked.value?.id) {
    return "checked-row";
  }
  return "";
};

defineExpose({
  getChecked,
  getCheckedList,
  handleQuery,
});
</script>

<style scoped>
.selector-wrap {
  padding: 10px;
  min-width: 600px;
}
</style>
